
package com.jojoteamwork.photo.download;

import com.jojoteamwork.photo.R;
import com.jojoteamwork.photo.util.Utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class DownloadTask extends AsyncTask<String, Integer, String> {
    private ProgressDialog mProgressDialog;

    // private FileDownloader downloader;

    private Context mContext;

    private DownloadFinishCallback mCallback;

    public DownloadTask(Context context, DownloadFinishCallback callback) {
        mContext = context;
        mCallback = callback;
    }

    @Override
    protected void onPreExecute() {
        mProgressDialog = new ProgressDialog(mContext);
        mProgressDialog.setMessage(mContext.getString(R.string.loading));
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);
        // mProgressDialog.setOnCancelListener(new OnCancelListener() {
        //
        // @Override
        // public void onCancel(DialogInterface dialog) {
        // DownloadTask.this.cancel(true);
        // dialog.cancel();
        // }
        // });
        mProgressDialog.show();
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {

        HttpClient client = new DefaultHttpClient();
        String path = params[0];
        String result = null;
        HttpGet get = new HttpGet(path);
        HttpResponse response;
        InputStream is = null;
        FileOutputStream fileOutputStream = null;
        try {
            response = client.execute(get);
            HttpEntity entity = response.getEntity();
            long length = entity.getContentLength();
            mProgressDialog.setMax((int) (length / 1024));
            is = entity.getContent();

            if (is != null) {
                String fileName = path.substring(path.lastIndexOf("/") + 1);
                File dir = new File(Utils.MAGAZINE_DIR);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                result = Utils.MAGAZINE_DIR + "/" + fileName;
                File file = new File(result);
                if (!file.exists()) {
                    file.createNewFile();
                }
                fileOutputStream = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int ch = -1;
                int count = 0;
                while ((ch = is.read(buf)) != -1) {
                    fileOutputStream.write(buf, 0, ch);
                    count += ch;
                    publishProgress((int) (count / 1024));
                }

            }
            fileOutputStream.flush();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        mProgressDialog.dismiss();
        mCallback.onFinish(result);
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        mProgressDialog.setProgress(values[0]);
        super.onProgressUpdate(values);
    }

    public interface DownloadFinishCallback {
        void onFinish(String filepath);
    }
}
